package com.jhws.common.pay.controller;

import com.jhws.common.base.bo.JsonRespData;
import com.jhws.business.car.bo.CarOrderPayModule;
import com.jhws.business.customer.bo.PayCustomer;
import com.jhws.business.customer.bo.PayCustomerSecret;
import com.jhws.business.customer.service.PayCustService;
import com.jhws.business.property.bo.PropertyFeePayModule;
import com.jhws.common.base.bo.Global;
import com.jhws.common.pay.bo.Order;
import com.jhws.common.pay.bo.PayConstants;
import com.jhws.common.pay.bo.PayModuleInfo;
import com.jhws.common.pay.service.OrderService;
import com.jhws.common.pay.service.WXPayService;

import com.jhws.sys.user.bo.TblUserDimBo;
import com.jhws.sys.user.service.ITblUserDimService;
import com.jhws.util.*;
import com.jhws.util.net.JhHttpClient;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Controller
@RequestMapping("/pay")
public class PayCtrl {

    @Resource
    OrderService IOrderService;
    @Resource
    WXPayService wxPayService;
    @Resource
    PayCustService payCustService;
    @Resource
    ITblUserDimService IUserService;

    @RequestMapping("getOrdersPage.x")
    @ResponseBody
    public JsonRespData getOrdersPage(String commCode,String dateStart,String dateEnd, String payModuleName){
        return new JsonRespData("",1,IOrderService.findOrdersPage(commCode,dateStart,dateEnd,payModuleName));
    }

    @RequestMapping("getOrders.x")
    @ResponseBody
    public JsonRespData getOrders(String commCode,String dateStart,String dateEnd, String payModuleName, Integer state){
        return new JsonRespData("",1,IOrderService.findOrders(commCode,dateStart,dateEnd,payModuleName,state));
    }

    @RequestMapping("getOrderDetail.x")
    @ResponseBody
    public JsonRespData getOrderDetail(Long orderId){
        return new JsonRespData("",1,IOrderService.getDetailInfoForOrder(orderId));
    }


    /**
     * 微信第三方平台扫码授权页面
     */
    @RequestMapping("getWeixin3rdAuthQRCodePage.x")
    public ModelAndView getWeixin3rdAuthQRCode(HttpServletRequest request, HttpServletResponse response) throws Exception{

        String domainName = request.getScheme() + "://" + request.getServerName();
        ModelAndView mv = new ModelAndView();

        String preAuthCode = wxPayService.get3rdPreAuthCode();

        LogHelper.t("preAuthCode : "+preAuthCode);
        Map map = GsonUtil.toObject(preAuthCode,Map.class);
        String url = PayConstants.WeixinURL3rdAuth +"?component_appid="+PayConstants.Weixin3rdCommServiceAppId+"&pre_auth_code="+map.get("pre_auth_code")+
                "&redirect_uri="+domainName+"/api/v2/pay/anon/weixin/3rdAuth/authCode&auth_type=1";

        LogHelper.t("AuthPageUrl : "+url);
        mv.addObject("weixinUrl",url);
        mv.setViewName("/business/pay/weixin3rdAuth");
        return mv;
    }

    /**
     * 获取已授权的公众号的信息
     * @return
     * @throws Exception
     */
    @RequestMapping("get3rdAuthedList.x")
    @ResponseBody
    public JsonRespData get3rdAuthedList() throws Exception{
        Map map = null;
        if(SecurityUtils.getSubject().hasRole(Global.ROLE_SUPPER_ADMIN)){
            map = payCustService.findCustomerSecretsPageByWhere("type='"+ PayConstants.PAY_TYPE_WEIXIN_H5+"'");
        }else{
            TblUserDimBo user = IUserService.currentUser();
            map = payCustService.findCustomerSecretsPageByWhere("type='"+ PayConstants.PAY_TYPE_WEIXIN_H5+"' and creator = '"+user.getLogName()+"'");
        }
        List<PayCustomerSecret> list = (List)map.get("list");
        JhHttpClient jhHttpClient = new JhHttpClient();
        List retList = new ArrayList();
        String accessToken = wxPayService.get3rdComponentAccessToken(null);
        Map params = new HashMap();
        params.put("component_appid",PayConstants.Weixin3rdCommServiceAppId);

        for(PayCustomerSecret secret : list){
            params.put("authorizer_appid",secret.getAppId());
            String json = jhHttpClient.post(PayConstants.WeixinUrl3rdGetAuthorizerInfo +"?component_access_token="+accessToken,GsonUtil.toJson(params));
            Map retMap = GsonUtil.toObject(json,Map.class);
            retMap.put("mchId",secret.getMchId());
            retMap.put("APISecret",secret.getSecret());
            retMap.put("id",secret.getId());
            retList.add(retMap);
        }

        map.put("list",retList);
        return new JsonRespData("",1,map);
    }

    /**
     * 获取支付宝的秘钥信息列表
     * @return
     */
    @RequestMapping("getAlipaySecretsPage.x")
    @ResponseBody
    public JsonRespData getAlipaySecretsPage(){
        Map map = null;
        if(SecurityUtils.getSubject().hasRole(Global.ROLE_SUPPER_ADMIN)){
            map = payCustService.findCustomerSecretsPageByWhere("type='"+ PayConstants.PAY_TYPE_ALIPAY+"'");
        }else{
            TblUserDimBo user = IUserService.currentUser();
            map = payCustService.findCustomerSecretsPageByWhere("type='"+ PayConstants.PAY_TYPE_ALIPAY+"' and creator = '"+user.getLogName()+"'");
        }

        return new JsonRespData("",1,map);
    }

    @RequestMapping("getPayTestQRCode.x")
    public void getPayTestQRCode(HttpServletRequest request,HttpServletResponse response) throws Exception{
        TblUserDimBo user = IUserService.currentUser();
        String domainName = request.getScheme() + "://" + request.getServerName();
        //禁止缓存
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Content-Disposition", "attachment;fileName=qrcode.jpg");
        List<PayCustomerSecret> secret = payCustService.getPayCustSecretByWhere("creator = '"+user.getLogName()+"' and type='"+PayConstants.PAY_TYPE_WEIXIN_H5+"'");
        String webUrl = "/api/v2/pay/anon/payTest?user="+user.getLogName()+"&appId="+(secret != null && secret.size()!=0?secret.get(0).getAppId():"");

        String url = domainName + webUrl;
        ImageIO.write(QRCodeUtil.createImage(url, null, true), "JPEG", response.getOutputStream());
        response.getOutputStream().flush();
    }

    /**
     * 获取某个小区的支付实体列表，比如小区，停车场等
     * @param commCode
     * @param modules
     * @return
     */
    @RequestMapping("getPayModulesInfo.x")
    @ResponseBody
    public JsonRespData getPayModulesInfo(String commCode,String [] modules){
        List<PayModuleInfo> list = new ArrayList<>();
        for(String module : modules){
            list.addAll(IOrderService.getPayModulesInfo(module,commCode));
        }
        return new JsonRespData("",1,list);
    }

    /**
     * 获取某个小区的已开通的支付实体列表
     * @param commCode
     * @return
     */
    @RequestMapping("getValidModulesForComm.x")
    @ResponseBody
    public JsonRespData getValidModulesForComm(String commCode){
        TblUserDimBo user = IUserService.currentUser();
        String [] modules = {PropertyFeePayModule.PROPERTY_FEE, CarOrderPayModule.PAY_MODULE};
        List<PayModuleInfo> list = new ArrayList<>();
        for(String module : modules){
            List<PayModuleInfo> payModuleInfoList = IOrderService.getPayModulesInfo(module,commCode);
            for(PayModuleInfo payModuleInfo : payModuleInfoList){
                if(payModuleInfo.getCustomId() != null){
                    PayCustomer payCustomer = payCustService.getPayCustomerById(payModuleInfo.getCustomId());
                    if(payCustomer!=null && user.getLogName().equals(payCustomer.getCreator()))
                        list.add(payModuleInfo);
                }
            }
        }
        return new JsonRespData("",1,list);
    }

    /**
     * 分配某个小区的支付实体与支付参数组之间的绑定关系
     * @param customId
     * @param payModuleInfosJson
     * @return
     * @throws Exception
     */
    @RequestMapping("assignPayModules.x")
    @ResponseBody
    public JsonRespData updatePayModulesForComm(Long customId,String payModuleInfosJson) throws Exception{
        List<PayModuleInfo> payModuleInfos = jsonUtil.getBeansFromJsonArray(payModuleInfosJson,PayModuleInfo.class);
        for(PayModuleInfo payModuleInfo : payModuleInfos){
            IOrderService.setModuleCustomId(payModuleInfo.getOrderType(),payModuleInfo.getId(),customId);
        }

        return new JsonRespData("",1,"");
    }

    /**
     * debug使用，为了设置已经生成的订单测试参数但是没有payModule属性
     * @return
     */
    @RequestMapping("debugSetPayModule.x")
    @ResponseBody
    public JsonRespData debugSetPayModule(){
        long now = System.currentTimeMillis();
        long gap =  1000L*3600L*24L*100L;
        int count = 0;
        String past = DateUtil.timestamp2String(now - gap,null);

        List<Order> orders = IOrderService.findOrders(null,past,DateUtil.getTimeNowFmtSec(),null,null);
        for(Order order : orders){
            if(order.getOrderType().equals(CarOrderPayModule.ORDER_CAR_MONTH) || order.getOrderType().equals(CarOrderPayModule.ORDER_CAR_LANE) ||
            order.getOrderType().equals(CarOrderPayModule.ORDER_CAR_ORDERED))
                order.setPayModule(CarOrderPayModule.PAY_MODULE);
            else if(order.getOrderType().equals(PropertyFeePayModule.PROPERTY_FEE))
                order.setPayModule(PropertyFeePayModule.PROPERTY_FEE);

            count++;
            IOrderService.save(order);
        }
        return new JsonRespData("",1,"修改了"+count+"条数据");
    }

}
